package com.insightfullogic.java8.examples.chapter8.dependency_inversion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by xiaohyb on 2015/12/8.
 */
public class FileHandler {

    // Formal
    public List<String> findHeadings(Reader input) {
        try (BufferedReader reader = new BufferedReader(input)) {
            return reader.lines()
                    .filter(line -> line.endsWith(":"))
                    .map(line -> line.substring(0, line.length() - 1))
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new HeadingLookupException(e);
        }
    }

    // Lambda
    public List<String> findHeadingsL(Reader reader) {
        return withLinesOf(reader,
                lines -> lines.filter(line -> line.endsWith(":"))
                        .map(line -> line.substring(0, line.length() - 1))
                        .collect(Collectors.toList()),
                HeadingLookupException::new);
    }

    private BufferedReader getBufferedReader(Reader input) {
        return new BufferedReader(input);
    }

    private <R> R withLinesOf(Reader input,
                              Function<Stream<String>, R> handler,
                              Function<IOException, RuntimeException> throwner) {
        try (BufferedReader reader = getBufferedReader(input)) {
            return handler.apply(reader.lines());
        } catch (IOException e) {
            throw throwner.apply(e);
        }
    }
}
